//
//  MyselfViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/20.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "MyselfViewController.h"
#import "LoginViewController.h"
#import "BlackManager.h"
#import "SetBlack.h"
#import "CollectionViewController.h"
@interface MyselfViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSArray *dataArr;
@property (nonatomic, assign)BOOL login;
@property (nonatomic, assign)CGFloat j;
@property (nonatomic, strong)UIView *topview;//上面灰色的区域
@end

@implementation MyselfViewController
//-(void)viewWillAppear:(BOOL)animated
//{
//     BOOL login = [[NSUserDefaults standardUserDefaults]boolForKey:@"register"];
//    if (login) {
//        UILabel *namelable = [[UILabel alloc]initWithFrame:CGRectMake(view.frame.size.width / 3 + 3, person.frame.origin.y + person.frame.size.height + 5, view.frame.size.width / 3, 25)];
//        NSString *nameStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
//        namelable.text = nameStr;
//        [view addSubview:namelable];
//    }else{
//        //其他登录方式按钮
//        UIView *otherView = [[UIView alloc]initWithFrame:CGRectMake(view.frame.size.width / 3 + 3, person.frame.origin.y + person.frame.size.height + 5, view.frame.size.width / 3, 25)];
//        otherView.backgroundColor = [UIColor lightGrayColor];
//        UILabel *moreLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, otherView.frame.size.width / 7 * 5, 30)];
//        //    moreLable.backgroundColor = [UIColor redColor];
//        moreLable.text = @"更多登录方式";
//        moreLable.font = [UIFont systemFontOfSize:14];
//        [otherView addSubview:moreLable];
//        otherView.layer.cornerRadius = 12;
//        otherView.clipsToBounds = YES;
//        moreLable.textColor = [UIColor whiteColor];
//        [view addSubview:otherView];
//        //进入箭头
//        UIImageView *goImg = [[UIImageView alloc]initWithFrame:CGRectMake(moreLable.frame.origin.x + moreLable.frame.size.width - 6, moreLable.frame.origin.y, otherView.frame.size.width / 7 * 2, moreLable.frame.size.height - 3)];
//        goImg.image = [UIImage imageNamed:@"iconfont-jinru-2"];
//        [otherView addSubview:goImg];
//    }
//
//    
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"我的";
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-back"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)] autorelease];
    
    //tableView
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Mcell"];
    [_tableView release];
    //tableView上面View
    self.topview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3 )];
    //登陆头像按钮
    UIButton *person = [UIButton buttonWithType:UIButtonTypeSystem];
    person.frame = CGRectMake(self.topview.frame.size.width / 10 * 4, self.topview.frame.size.height / 6, self.topview.frame.size.width / 5, self.topview.frame.size.width / 5);
    person.layer.cornerRadius = self.view.frame.size.width / 10;
    person.clipsToBounds = YES;
    [person setBackgroundImage:[UIImage imageNamed:@"qiaoba.png"] forState:UIControlStateNormal];
    [person addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [self.topview addSubview:person];
    //判断是否登陆改变页面上部样式
    self.login = [[NSUserDefaults standardUserDefaults]boolForKey:@"register"];
    if (_login) {
        //如果登陆了下方是用户名的lable
        UILabel *namelable = [[UILabel alloc]initWithFrame:CGRectMake(self.topview.frame.size.width / 3 + 3, person.frame.origin.y + person.frame.size.height + 5, self.topview.frame.size.width / 3, 25)];
        NSString *nameStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];
        namelable.text = nameStr;
        namelable.textAlignment = NSTextAlignmentCenter;
        [self.topview addSubview:namelable];
        [namelable release];
    }else{
    //其他登录方式按钮
    UIView *otherView = [[UIView alloc]initWithFrame:CGRectMake(self.topview.frame.size.width / 3 + 3, person.frame.origin.y + person.frame.size.height + 5, self.topview.frame.size.width / 3, 25)];
    otherView.backgroundColor = [UIColor lightGrayColor];
    UILabel *moreLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, otherView.frame.size.width / 7 * 5, 30)];
//    moreLable.backgroundColor = [UIColor redColor];
    moreLable.text = @"更多登录方式";
    moreLable.font = [UIFont systemFontOfSize:14];
    [otherView addSubview:moreLable];
    [moreLable release];
    otherView.layer.cornerRadius = 12;
    otherView.clipsToBounds = YES;
    moreLable.textColor = [UIColor whiteColor];
    [self.topview addSubview:otherView];
    [otherView release];
    //进入箭头
    UIImageView *goImg = [[UIImageView alloc]initWithFrame:CGRectMake(moreLable.frame.origin.x + moreLable.frame.size.width - 6, moreLable.frame.origin.y, otherView.frame.size.width / 7 * 2, moreLable.frame.size.height - 3)];
    goImg.image = [UIImage imageNamed:@"iconfont-jinru-2"];
    [otherView addSubview:goImg];
    [goImg release];
    }
    _tableView.tableHeaderView = _topview;
    
    self.dataArr =
    
  @[@"离线", @"收藏", @"清除缓存", @"夜间模式"];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        CollectionViewController *collectionVC = [[CollectionViewController alloc]init];
        [self.navigationController pushViewController:collectionVC animated:YES];
    }
    if (indexPath.row == 2) {
        //创建管理器对象
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //获取沙河路径
        NSString *catch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSLog(@"%@", NSHomeDirectory());
        if ([fileManager fileExistsAtPath:catch]) {
            NSArray *files = [fileManager subpathsAtPath:catch];
            //遍历所有文件
            for (NSInteger i = 0; i < files.count; i++) {
                NSString *filePath = [catch stringByAppendingPathComponent:files[i]];
                //获取文件大小
                float k = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
                self.j =  self.j + k;
                
            }
        }
        NSString *size = [NSString stringWithFormat:@"是否清除%.2fM大小",_j / 1024 / 1024];
       //创建弹窗
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:size preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消");
        }];
        [alter addAction:cancle];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"确定");
            //删除整个Caches文件夹
//            [fileManager removeItemAtPath:catch error:nil];
            self.j = 0;
            //遍历删除Caches文件夹里的每个文件
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                               NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                               
                               NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                               NSLog(@"files :%lu",(unsigned long)[files count]);
                               for (NSString *p in files) {
                                   NSError *error;
                                   NSString *path = [cachPath stringByAppendingPathComponent:p];
                                   if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                       [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                                   }
                               }
                               [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
            
        }];
        [alter addAction:yesAction];
//        [_tableView reloadData];
        //弹出弹窗
        [self presentViewController:alter animated:YES completion:^{
            //
        }];
    }
}
-(void)clearCacheSuccess
{
    NSLog(@"清理成功");
    
}
-(void)setNightDayModel
{
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
//    [SetBlack setBackgroundColorWithView:_tableView];
    
}
-(void)setLightDayModel
{
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
//    [SetBlack setBackgroundColorWithView:_tableView];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Mcell"];
    [SetBlack setCellColorWithCell:cell];
    if (indexPath.row < 4) {
        [SetBlack setLableTitleColorWithArr:@[cell.textLabel]];
        if (indexPath.row == 3) {
            UISwitch *kaiguan = [[UISwitch alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 60, 10, 50, 20)];
            kaiguan.on = [BlackManager sharedInstance].isNight;
            [cell addSubview:kaiguan];
            [kaiguan addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
            [kaiguan release];
            
        }else{
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = _dataArr[indexPath.row];
        //改变topView的背景颜色
        if ([BlackManager sharedInstance].isNight) {
            self.topview.backgroundColor = [UIColor blackColor];
        }else{
            self.topview.backgroundColor = [UIColor grayColor];
        }

    }
    return cell;
}
-(void)switchAction:(UISwitch *)kaiguan
{
    if (kaiguan.on) {
        //设置isNight属性的时候就执行set方法 发送夜间还是白天的通知 然后其他页面接到通知执行BaseViewController里的方法
        [BlackManager sharedInstance].isNight = ![BlackManager sharedInstance].isNight;
         self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    }else{
        [BlackManager sharedInstance].isNight = ![BlackManager sharedInstance].isNight;
         self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }
    _tableView.backgroundColor = [UIColor whiteColor];
    [_tableView reloadData];
}
//登陆
-(void)loginAction
{
    if (_login) {
        
    }else{
    LoginViewController *login = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:login animated:YES];
        [login release];
    NSLog(@"登录");
    }
    
}
//返回按钮方法
-(void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        //
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
